package com.rjpacket.supernews.app;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.rjpacket.supernews.app.adapters.NewsFragmentAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.rjpacket.supernews.app.adapters.SearchAdapter;
import com.rjpacket.supernews.app.adapters.SearchDetailAdapter;
import com.rjpacket.supernews.app.models.News;
import com.rjpacket.supernews.app.models.NewsDetail;
import com.rjpacket.supernews.app.models.Search;
import com.rjpacket.supernews.app.task.FunnyNewsDetailTask;
import com.rjpacket.supernews.app.task.FunnyNewsListTask;
import com.rjpacket.supernews.app.task.NewsSearchTask;
import com.rjpacket.supernews.app.tasks.DetailTaskCallOnBack;
import com.rjpacket.supernews.app.tasks.TaskCallOnBack;
import com.rjpacket.supernews.app.utils.HttpTool;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedList;
import java.util.List;


public class NewsSearchActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener, DetailTaskCallOnBack, TaskCallOnBack {

    private ListView listView;
    //存储
    private List<List<String>> data;

    private JSONObject json;

    private SearchAdapter adapter;
    //下一次热门搜索的页面标记
    private int page;
    //
    private List<String> list;

    private ListView listView2;

    private LinearLayout search1;

    private LinearLayout search2;

    private EditText editText;

    private SearchDetailAdapter adapter1;

    private List<News> Nid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_news_search);

        listView = (ListView) findViewById(R.id.search_news_listView_01);

        listView2 = (ListView) findViewById(R.id.search_news_listView_02);

        listView.setOnItemClickListener(this);

        listView2.setOnItemClickListener(this);

        search1 = (LinearLayout) findViewById(R.id.search_main_01);

        search2 = (LinearLayout) findViewById(R.id.search_main_02);

        editText = (EditText) findViewById(R.id.search_edit);


        TextView actionBar = (TextView) findViewById(R.id.actionbar_title);

        actionBar.setText("新闻搜索");

        //listView = (ListView)findViewById(R.id.search_news_listView_01);
        View btn = findViewById(R.id.search_image_btn);

        btn.setOnClickListener(this);

    }

    public void ImageOnClick(View view) {
        //初始化传递的news信息
        Nid = new LinkedList<News>();
        //简单的隐藏
        search1.setVisibility(View.GONE);

        search2.setVisibility(View.VISIBLE);

        list = new LinkedList<String>();

        String s = editText.getText().toString().trim();

        InputAsync inputAsync = new InputAsync();

        try {

            inputAsync.execute(Constants.SEARCH_DETAIL_URL + URLEncoder.encode(s, "UTF-8"));

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }

        adapter1 = new SearchDetailAdapter(list, this);

        listView2.setAdapter(adapter1);

    }


    @Override
    public void onClick(View view) {

        search1.setVisibility(View.VISIBLE);

        search2.setVisibility(View.GONE);

        data = new LinkedList<List<String>>();

        MyAsync task = new MyAsync();

        task.execute(Constants.SEARCH_NEWS + Integer.toString(page));

        adapter = new SearchAdapter(this, data);

        listView.setAdapter(adapter);

        page += 1;
    }

    //ListView点击事件
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        switch (adapterView.getId()) {

            case R.id.search_news_listView_01:

                break;
            case R.id.search_news_listView_02:
                //解析出每一次输入关键字条目信息
                NewsSearchTask newsSearchTask = new NewsSearchTask(this);

                String s = list.get(i);

                String url = null;

                try {
                    url = Constants.SEARCH_DETAIL_URL_ENTER + URLEncoder.encode(s, "UTF-8") + "&size=30";

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();

                }

                newsSearchTask.execute(url);

                Intent intent = new Intent(this, FunnyNewsDetailActivity.class);

                News news = Nid.get(0);

                intent.putExtra("news", news.getNewsDetail());

                startActivity(intent);

                break;

        }
    }

    //实现详情回调接口
    @Override
    public void callBack(Object object, String position) {

        if (object != null && object instanceof JSONObject) {

            JSONObject json = (JSONObject) object;

            NewsDetail detail = new NewsDetail();

            detail.parseJSON(json);

            News news = Nid.get(0);

            news.setNewsDetail(detail);
        }
    }

    //实现条目回调接口
    @Override
    public void callOnBack(Object object) {

        if (object != null && object instanceof JSONObject) {
            //////////解析出返回数据的stime，sequence
            JSONObject result = (JSONObject) object;

            News news = new News();

            news.parseJSON(result);

            List<News> newsList = news.getList();

            News item = newsList.get(0);

            String nid = item.getNid();
            //不同item的不同接口网址
            String detailUrl = Constants.YULE_ITEM_URL + nid;

            FunnyNewsDetailTask task = new FunnyNewsDetailTask(this);

            task.execute(detailUrl);

            Nid.addAll(newsList);

        } else {
            //TODO 请检查网络
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        }
    }


    //解析热门搜索的异步任务
    private class MyAsync extends AsyncTask<String, Integer, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... strings) {

            JSONObject ret = null;

            byte[] bytes = HttpTool.get(strings[0]);

            if (bytes != null) {

                try {

                    String str = new String(bytes, "UTF-8");

                    json = new JSONObject(str);

                    Search s = new Search();

                    s.parseJSON(json);

//                  data = s.getList();

                    data.addAll(s.getList());

                    System.out.println();

                    Log.d("------", data + "");

                    ret = json;

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();

                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

            return ret;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {

            adapter.notifyDataSetChanged();

        }
    }

    //解析搜索框输入的异步任务

    private class InputAsync extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... strings) {

            String url = strings[0];

            byte[] bytes = HttpTool.get(url);

            try {
                String str = new String(bytes, "UTF-8");

                JSONArray array = new JSONArray(str);

                for (int i = 0; i < array.length(); i++) {

                    list.add(array.getString(i));

                }
            } catch (UnsupportedEncodingException e) {

                e.printStackTrace();

            } catch (JSONException e) {

                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

            adapter1.notifyDataSetChanged();
        }
    }

   /* private class DetailAsync extends AsyncTask<String,Integer,String>{
        String ret = null;
        @Override
        protected String  doInBackground(String... strings) {
            String url = strings[0];
            byte[] bytes = HttpTool.get(url);
            try {
                String str = new String(bytes, "UTF-8");
                JSONObject jsonObject = new JSONObject(str);
                News news = new News();
                news.parseJSON(jsonObject);
                List<News> newsList = news.getList();
                for (int i = 0; i < newsList.size(); i++) {
                    News item = newsList.get(i);
                    String nid = item.getNid();
                    //不同item的不同接口网址
                    String detailUrl = Constants.YULE_ITEM_URL + nid;

                    FunnyNewsDetailTask task = new FunnyNewsDetailTask(NewsSearchActivity.this);
                    task.execute(detailUrl, i + "");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return ret;
        }
    }*/
}
